package com.iwhalecloud.bss.kite.cucc.service.attr.handler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.dataservice.cache.ProductCache;
import com.iwhalecloud.bss.pub.client.constanst.Symbols;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.iwhalecloud.bss.kite.common.cache.impl.KiteContextCache;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.service.attr.LocalQuerySeqHelper;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInstFunc;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.service.attr.handler.AbstractAttrHandler;

import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;

/**
 *
 */
public class NameAutoCreateAttrHandler<I extends KiteInst, D extends AttrData>
    extends AbstractAttrHandler<KiteInst, AttrData> {
    @Autowired
    IQuerySceneInstService querySceneInstService;

    @Override
    public void after(KiteAttr attr, KiteInst inst, AttrData data) {
        if (ActionType.A.equals(inst.getActionType()) && KiteStringUtils.isEmpty(attr.getValue())) {
            this.deal(attr, inst, data);
        }
        // 是 k的时候要判断,状态是有效
        if ("K".equals(attr.getIsEdit())) {
            if (KeyConsts.STATE_USING.equals(
                inst.getStateCd()) /* && ServiceOfferConsts.SERVICE_OFFER_MODIFY .equals(data.getServiceOfferId()) */) {
                attr.setIsEdit(KeyConsts.IFTRUE_F);
                String isEditImg = KeyConsts.POP.equals(attr.getAttrValueTypeId()) ?
                    KeyConsts.IFTRUE_F :
                    attr.getIsEditImg();
                attr.setIsEditImg(isEditImg);
            }
            else {
                String isEdit = !KeyConsts.POP.equals(attr.getAttrValueTypeId()) ?
                    KeyConsts.IFTRUE_T :
                    KeyConsts.IFTRUE_F;
                String isEditImg = KeyConsts.POP.equals(attr.getAttrValueTypeId()) ?
                    KeyConsts.IFTRUE_T :
                    attr.getIsEditImg();
                attr.setIsEdit(isEdit);
                attr.setIsEditImg(isEditImg);
            }
        }
    }

    private void deal(KiteAttr attr, KiteInst inst, AttrData data) {
        /*if (!CuccServiceContext.getIsCallInfForInitAttr()) {
            return;
        }*/
        // 重提初始化场景初始化过程不处理
        Map<String, Object> extParams = ContextUtil.getLoginInfo().getUserInfo().getExtParams();
        if (KiteMapUtils.isNotEmpty(extParams) && extParams.containsKey("nodeCode")) {
            return;
        }
        // 二次业务的场景初始化过程不处理
        if (!KiteStringUtils.equalsAny(data.getServiceOfferId(), LocalServiceOfferConsts.SERVICE_OFFER_RESOURCE_CHECK, ServiceOfferConsts.SERVICE_OFFER_ORDER)
            && !KeyConsts.IFTRUE_T.equals(querySceneInstService.getExtParameterValue(data.getSceneInstId(), LocalKeyConsts.BUSI_CHANGE))
            && !"workOrder".equals(querySceneInstService.getExtParameterValue(data.getSceneInstId(), "initSource"))) {
            return;
        }
        // 兼容融合商品处理逻辑: 通过功能产品找到当前套餐非加装角色接入产品,获取产品的"业务号码"属性值。
        KiteAttr accAttr = null;
        if (inst instanceof KiteProdInstFunc) {
            KiteProdInst prodInst = querySceneInstService //资费产品
                .getProdInstByFuncProdInstId(data.getCustId(), inst.getInstId());
            if (!KiteObjectUtils.isEmpty(prodInst) && KiteStringUtils.isNotEmpty(prodInst.getProdInstId())) {
                accAttr = getServiceNumAttr(data, accAttr, prodInst);
            }
        }
        else if (inst instanceof KiteProdInst && KiteStringUtils.isNotEmpty(((KiteProdInst) inst).getProdInstId())) {
            accAttr = getServiceNumAttr(data, accAttr, (KiteProdInst) inst);
        }
        if (KiteObjectUtils.isEmpty(accAttr)) {
            accAttr = querySceneInstService.getCommonAttrsByFieldName(data.getSceneInstId(), "business_number", "113");
        }
        if (Objects.nonNull(accAttr)) {
            String name = accAttr.getValue();
            CuccContextCustDTO custDTO = KiteContextCache.get(KiteStringUtils.join(ContextUtil.getHttpSessoinId(), Symbols.HASH, data.getCustId(), Symbols.AT, "custInfo"));
            String zfStr = DcPublicCache.getCodea("202012170001", "zf");
            if (LocalKeyConsts.FUNC_PROD_ID_APN.equals(inst.getSpecId()) || LocalKeyConsts.FUNC_PROD_ID_NBAPN
                .equals(inst.getSpecId()) || LocalKeyConsts.FUNC_PROD_ID_5GAPN.equals(inst.getSpecId()) || LocalKeyConsts.FUNC_PROD_ID_YF5GAPN.equals(inst.getSpecId())) {
                // 序列
                Map<String, String> inParam = new HashMap<>();
                inParam.put("SEQ_TYPE", "WLW_APN_ID");
                inParam.put("SYS_TYPE", "1");
                inParam.put("SYS_SOURCE", "");
                String seq = LocalQuerySeqHelper.getSeqBySeqType(inParam, data.getSceneInstId(), custDTO);
                name = name + "_APN_" + seq;
            }
            else if (LocalKeyConsts.FUNC_PROD_ID_TX.equals(inst.getSpecId()) || LocalKeyConsts.FUNC_PROD_ID_NBTX
                .equals(inst.getSpecId()) || LocalKeyConsts.FUNC_PROD_ID_5GTX.equals(inst.getSpecId()) || LocalKeyConsts.FUNC_PROD_ID_YF5GTX.equals(inst.getSpecId())) {
                // 序列
                Map<String, String> inParam = new HashMap<>();
                inParam.put("SEQ_TYPE", "WLW_COMMUNICATE_ID");
                inParam.put("SYS_TYPE", "1");
                inParam.put("SYS_SOURCE", "");
                String seq = LocalQuerySeqHelper.getSeqBySeqType(inParam, data.getSceneInstId(), custDTO);
                name = name + "_TX_" + seq;
            }
            else if (StringUtils.indexOf(zfStr, inst.getSpecId()) > -1) {
                // 序列
                Map<String, String> inParam = new HashMap<>();
                inParam.put("SEQ_TYPE", "WLW_RATEPLAN_ID");
                inParam.put("SYS_TYPE", "1");
                inParam.put("SYS_SOURCE", "");
                String seq = LocalQuerySeqHelper.getSeqBySeqType(inParam, data.getSceneInstId(), custDTO);
                name = name + "_ZF_" + seq;
                // 200003698 资费计划名称
                if (KiteStringUtils.equals("200003698", attr.getFieldName())) {
                    name = "待生成";
                }
            }
            else if (LocalKeyConsts.FUNC_PROD_ID_5GQP.equals(inst.getSpecId())) {
                // 序列
                Map<String, String> inParam = new HashMap<>();
                inParam.put("SEQ_TYPE", "WLW_APN_ID");
                inParam.put("SYS_TYPE", "1");
                inParam.put("SYS_SOURCE", "");
                String seq = LocalQuerySeqHelper.getSeqBySeqType(inParam, data.getSceneInstId(), custDTO);
                name = name + "_5GQP_" + seq;
            }
            attr.setValue(name);
            attr.setValueDesc(name);
            attr.setDefaultValue(name);
            super.set(attr, inst, name, data);
        }
    }

    private KiteAttr getServiceNumAttr(AttrData data, KiteAttr accAttr, KiteProdInst prodInst) {
        KiteOfferInst offerInst = this.querySceneInstService
            .getMainOfferInstByProdInstId(data.getCustId(), prodInst.getProdInstId()); //4G套餐
        if (!KiteObjectUtils.isEmpty(offerInst)) {
            List<KiteProdInst> prodInsts = this.querySceneInstService
                .listProdInstsFromOfferInst(data.getCustId(),
                    offerInst.getOfferInstId()); //获取当前套餐下的所有成员产品,遍历每个产品获取业务号码
            if (KiteListUtils.isNotEmpty(prodInsts)) {
                KiteProdInst accessProdInst = prodInsts.stream()
                    .filter(kiteProdInst -> !KiteObjectUtils.isEmpty(kiteProdInst.getAttr("200002981"))).findFirst()
                    .orElse(null);
                accAttr = accessProdInst != null ? accessProdInst.getAttr("200002981") : null;
                // 如果业务号码没生成，主动调服务生成业务号码
                if (Objects.nonNull(accAttr) && KiteStringUtils.isEmpty(accAttr.getValue())) {
                    LocalGenNumberAttrHandler handler = SpringUtil.getBean(LocalGenNumberAttrHandler.class);
                    handler.createSerialNumber(accAttr, accessProdInst, data);
                }
            }
        }
        return accAttr;
    }

    @Override
    public void set(KiteAttr attr, KiteInst inst, String value, AttrData data) {
        super.set(attr, inst, value, data);
        //模版还原时，需要生成新的标识
        if ("sceneTempl".equals(data.getExtAttributes().get("entry"))) {
            this.deal(attr, inst, data);
        }
    }

}
